<?php

namespace app\api\model\xyvenue\store;

use think\Model;


class Service extends Model
{

    // 表名
    protected $name = 'xyvenue_store_service';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];

    //列表动态隐藏字段
    public static $list_hidden = ['updatetime'];


    /**
     * params 请求参数
     */
    public static function getServiceList($params)
    {
        extract($params);
        $where = [
            'status' => 'normal'
        ];
        $order = 'weigh desc';

        if (isset($ids) && $ids !== '') {
            $order = 'field(id, ' . $ids . ')';
            $idsArray = explode(',', $ids);
            $where['id'] = ['in', $idsArray];
        }

        $service = self::where($where);

        $order = xyvenueFilterSql($order);
        $service = $service->field('*')->orderRaw($order)->order('id desc');

        $cacheKey = 'servicelist-' . (isset($page) ? 'page' : 'all') . '-' . md5(json_encode($params));

        // 判断缓存
        $serviceCache = cache($cacheKey);
        if ($serviceCache) {
            // 存在缓存直接 返回
            $serviceCache = json_decode($serviceCache, true);
            return $serviceCache ? : [];
        } 

        if (isset($page)) {
            $service = $service->paginate($per_page ?? 10);
            $serviceData = $service->items();
        } else {
            $service = $serviceData = $service->select();
        }

        $data = [];
        if ($serviceData) {
            $collection = collection($serviceData);
            $data = $collection->hidden(self::$list_hidden);
        }

        if (isset($page)) {
            $service->data = $data;
        } else {
            $service = $data;
            cache($cacheKey, json_encode($service), (600 + mt_rand(0, 300)));
        }

        return $service;
    }

    public function getLogoimageAttr($value, $data)
    {
        if (!empty($value)) return cdnurl($value, true);
    }
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    
    public function getStatusList()
    {
        return ['normal' => __('Normal'),'hidden'=>__('Hidden')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }




}
